package view;

import model.LibrarySystem;
import model.Resource;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.List;

public class SearchPanel extends JPanel {
    private final LibrarySystem system;
    private final MainFrame mainFrame;
    private JTextField searchField;
    private JButton searchButton;
    private JComboBox<String> typeComboBox;
    private JList<Resource> resultList;
    private DefaultListModel<Resource> listModel;

    public SearchPanel(LibrarySystem system, MainFrame mainFrame) {
        this.system = system;
        this.mainFrame = mainFrame;
        setLayout(new BorderLayout(10, 10));
        setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
        initComponents();
    }

    private void initComponents() {
        // 搜索区域
        JPanel topPanel = new JPanel(new BorderLayout(10, 10));

        // 搜索框和按钮
        JPanel searchBoxPanel = new JPanel();
        searchBoxPanel.setLayout(new BoxLayout(searchBoxPanel, BoxLayout.X_AXIS));

        searchField = new JTextField(30);
        searchField.setFont(new Font("微软雅黑", Font.PLAIN, 14));

        searchButton = new JButton("搜索");
        searchButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        searchButton.setBackground(new Color(70, 130, 180));
        searchButton.setForeground(Color.WHITE);

        searchButton.addActionListener(this::performSearch);
        searchField.addActionListener(this::performSearch);

        searchBoxPanel.add(searchField);
        searchBoxPanel.add(Box.createHorizontalStrut(10));
        searchBoxPanel.add(searchButton);

        // 类型选择
        JPanel filterPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        filterPanel.add(new JLabel("资源类型:"));
        typeComboBox = new JComboBox<>(new String[]{"所有类型", "图书", "杂志", "DVD"});
        typeComboBox.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        filterPanel.add(typeComboBox);

        // 添加快速跳转按钮
        JButton toBorrowBtn = new JButton("前往借阅");
        toBorrowBtn.addActionListener(e -> mainFrame.showPanel("borrow"));
        toBorrowBtn.setBackground(new Color(50, 205, 50));
        toBorrowBtn.setForeground(Color.WHITE);
        filterPanel.add(toBorrowBtn);

        topPanel.add(searchBoxPanel, BorderLayout.CENTER);
        topPanel.add(filterPanel, BorderLayout.SOUTH);

        add(topPanel, BorderLayout.NORTH);

        // 结果列表
        listModel = new DefaultListModel<>();
        resultList = new JList<>(listModel);
        resultList.setCellRenderer(new ResourceListRenderer());
        resultList.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        resultList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        resultList.setFixedCellHeight(60);

        resultList.addListSelectionListener(e -> {
            if (!e.getValueIsAdjusting()) {
                Resource selected = resultList.getSelectedValue();
                if (selected != null) {
                    mainFrame.showResourceDetails(selected);
                }
            }
        });

        JScrollPane scrollPane = new JScrollPane(resultList);
        scrollPane.setBorder(BorderFactory.createTitledBorder("搜索结果"));
        add(scrollPane, BorderLayout.CENTER);

        // 初始显示所有资源
        performSearch(null);
    }

    private void performSearch(ActionEvent e) {
        String query = searchField.getText().trim();
        String type = (String) typeComboBox.getSelectedItem();

        List<Resource> results = system.findResource(query);

        // 按类型过滤
        if (!"所有类型".equals(type)) {
            String typeName = type.toLowerCase();
            results.removeIf(res -> !res.getClass().getSimpleName().equalsIgnoreCase(typeName));
        }

        listModel.clear();
        for (Resource res : results) {
            listModel.addElement(res);
        }
    }

    public void refresh() {
        performSearch(null);
    }

    // 自定义列表渲染器
    private static class ResourceListRenderer extends DefaultListCellRenderer {
        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value, int index,
                                                      boolean isSelected, boolean cellHasFocus) {
            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            if (value instanceof Resource) {
                Resource res = (Resource) value;
                setText(String.format("<html><b>%s</b> - %s<br><font color='gray'>类型: %s | ID: %s</font></html>",
                        res.getTitle(),
                        getShortDetails(res),
                        res.getClass().getSimpleName(),
                        res.getId()));

                if (res.isAvailable()) {
                    setIcon(UIManager.getIcon("OptionPane.informationIcon"));
                } else {
                    setIcon(UIManager.getIcon("OptionPane.warningIcon"));
                }

                if (isSelected) {
                    setBackground(new Color(70, 130, 180));
                    setForeground(Color.WHITE);
                } else {
                    setBackground(list.getBackground());
                    setForeground(list.getForeground());
                }
            }
            return this;
        }

        private String getShortDetails(Resource res) {
            if (res instanceof model.Book) {
                return "作者: " + ((model.Book) res).getAuthor();
            } else if (res instanceof model.Magazine) {
                return "期号: " + ((model.Magazine) res).getIssueNumber();
            } else if (res instanceof model.DVD) {
                return "导演: " + ((model.DVD) res).getDirector();
            }
            return "";
        }
    }
}